<template>
  <el-select
    v-model="currentValue"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    :filterable="filterable"
    :size="size"
    :style="{ width: width }"
    @change="handleChange"
    @clear="handleClear"
  >
    <el-option
      v-for="company in companyOptions"
      :key="company.deptId"
      :label="company.deptName"
      :value="company.deptId"
    />
  </el-select>
</template>

<script>
import { listDept } from "@/api/system/dept";

export default {
  name: "CompanySelect",
  props: {
    value: {
      type: [String, Number],
      default: null
    },
    placeholder: {
      type: String,
      default: "请选择公司"
    },
    clearable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    filterable: {
      type: Boolean,
      default: true
    },
    size: {
      type: String,
      default: ""
    },
    width: {
      type: String,
      default: "100%"
    }
  },
  data() {
    return {
      companyOptions: [],
      loading: false
    };
  },
  computed: {
    currentValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      }
    }
  },
  created() {
    this.getCompanyList();
  },
  methods: {
    /** 获取公司列表 */
    getCompanyList() {
      this.loading = true;
      listDept({ parentId: 100 }).then(response => {
        this.companyOptions = response.data || [];
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 选择变化 */
    handleChange(value) {
      this.$emit('input', value);
      this.$emit('change', value);
      
      // 查找选中的公司信息
      const selectedCompany = this.companyOptions.find(item => item.deptId === value);
      this.$emit('company-change', selectedCompany);
    },
    /** 清空选择 */
    handleClear() {
      this.$emit('input', null);
      this.$emit('change', null);
      this.$emit('clear');
      this.$emit('company-change', null);
    },
    /** 刷新数据 */
    refresh() {
      this.getCompanyList();
    }
  }
};
</script>

<style scoped>
</style> 